package com.guochu.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

/**
 * @Author: luc
 * @Date: 2019-10-10 10:39
 */
public class CommonHelper {

    /**
     * 自动生成编号  201008251145409865
     *
     * @return String  21位编号
     */
    public static String CreateNo() {
        Random random = new Random();
        //生成编号 , int强转属于截尾法
        //int intRandom = (int) (random.nextInt(1) * (10000 - 1000) + 1000);
        int intRandom= (int)(Math.random()*(99999-10000 + 1))+ 10000;

        //形如
        return DateHelper.getDateString(new Date(), "yyyyMMddHHmmssSSS") + intRandom;
    }

    /**
     * 提供精确的乘法运算。
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static double mul(double v1,double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

        /**
         * 利用反射，通过属性名获取属性值
         *
         * @param obj
         * @param fieldName
         * @return
         * @throws InvocationTargetException
         * @throws IllegalAccessException
         * @throws NoSuchMethodException
         */
    public static Object getFieldValueByName(Object obj, String fieldName) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        Method method = obj.getClass().getMethod(getter, new Class[]{});
        Object value = method.invoke(obj, new Object[]{});
        return value;
    }

    /**
     * 利用反射，给指定属性赋值
     *
     * @param obj
     * @param fieldName
     * @param value
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void setFieldValueByName(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        // 获取obj类的字节文件对象
        Class c = obj.getClass();
        // 获取该类的成员变量
        Field f = c.getDeclaredField(fieldName);
        // 取消语言访问检查
        f.setAccessible(true);
        // 给变量赋值
        f.set(obj, value);
    }
}
